package com.aliyun.config;


import com.alipay.v3.ApiClient;
import com.alipay.v3.ApiException;
import com.alipay.v3.util.model.AlipayConfig;
import com.aliyun.pojo.pay.AliyunPay;
import com.aliyun.properties.AliyunProperties;
import com.aliyun.service.impl.AliyunCredentialsService;
import com.aliyun.service.impl.AliyunOssService;
import com.aliyun.service.impl.AliyunPayService;
import com.aliyun.service.impl.AliyunSmsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@ComponentScan(basePackages = "com.aliyun.service.impl")
public class AliyunConfiguration {

    @Bean
    public AliyunProperties aliyunProperties(){
        return new AliyunProperties();
    }

    @Bean
    public AliyunCredentialsService aliyunCredentialsService(){
        return new AliyunCredentialsService(aliyunProperties());
    }

    @Bean
    public AliyunOssService aliyunOssService(){
        return new AliyunOssService();
    }

    @Bean
    public AliyunSmsService aliyunSmsService(){
        return new AliyunSmsService();
    }

    @Bean
    public AliyunPayService aliyunPayService(){
        return new AliyunPayService();
    }

    @Bean
    public ApiClient apiClient(){
        ApiClient apiClient = com.alipay.v3.Configuration.getDefaultApiClient();
        try {
            apiClient.setAlipayConfig(alipayConfig());
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
        return apiClient;
    }

    @Bean
    public AlipayConfig alipayConfig(){
        AlipayConfig alipayConfig = new AlipayConfig();
        AliyunPay aliyunPay = aliyunProperties().getPay();
        if (aliyunPay != null){
            alipayConfig.setServerUrl(aliyunPay.getGate_way());
            alipayConfig.setAppId(aliyunPay.getApp_id());
            alipayConfig.setPrivateKey(aliyunPay.getPrivate_key());
            alipayConfig.setAlipayPublicKey(aliyunPay.getPublic_key());
        }
        return alipayConfig;
    }


    @Bean(name = "aliyunThreadPoolExecutor")
    public ThreadPoolExecutor aliyunThreadPoolExecutor() {
        int processors = Runtime.getRuntime().availableProcessors();
        return new ThreadPoolExecutor(processors,
                processors * 2,
                5,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(1024),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy());
    }


}
